import os
import json
import pandas as pd
step1_preprocess, step2_create_batch, step3_run_batch
from utils import save_dataframe


def create_and_save_batch(input_excel):
    """创建批量任务并保存任务信息"""
    print("步骤1: 预处理Excel...")
    full_df, symbol_df, text_df = step1_preprocess.preprocess_excel(input_excel)

    # 保存预处理结果
    save_dataframe(full_df, "完整文档.xlsx")
    save_dataframe(symbol_df, "纯符号内容.xlsx")
    save_dataframe(text_df, "文本内容.xlsx")

    print("\n步骤2: 创建批量任务文件...")
    batch_file = step2_create_batch.create_batch_file(text_df)
    print(f"批量任务文件已创建: {batch_file}")

    print("\n步骤3: 运行批量任务...")
    batch_id = step3_run_batch.run_batch_job(batch_file)
    print(f"批量任务ID: {batch_id}")

    # 创建任务信息文件
    job_info = {
        "input_excel": input_excel,
        "batch_file": batch_file,
        "batch_id": batch_id,
        "symbol_file": os.path.abspath("output/纯符号内容.xlsx"),
        "full_file": os.path.abspath("output/完整文档.xlsx"),
        "text_file": os.path.abspath("output/文本内容.xlsx"),
        "status": "created"
    }

    # 保存任务信息
    job_info_path = f"job_{batch_id}.json"
    with open(job_info_path, 'w', encoding='utf-8') as f:
        json.dump(job_info, f, ensure_ascii=False, indent=2)

    print(f"\n任务信息已保存至: {job_info_path}")
    print("请运行 check_batch_status.py 来检查任务状态并获取结果")

    return job_info_path


if __name__ == "__main__":
    input_file = "5 英文招股书——历史、重组及公司架构_5 中文招股书——历史、重组及公司架构_20250630_105740.xlsx"
    job_info_path = create_and_save_batch(input_file)